import { useEffect, useState } from 'react';

const DEFAULT_SETTINGS = {
  model: 'deepseek-chat',
  temperature: 0.3,
  enableCoT: false,
  cotMode: 'ZERO_SHOT',
  cotExample: '',
  chatMode: 'BASIC',
  showToolResults: true,
  imageUrls: [],
  prompt: '你是一个乐于助人的 AI 智能助手',
};

function loadSessionSettings(sessionId) {
  if (!sessionId) return { ...DEFAULT_SETTINGS };
  try {
    const raw = localStorage.getItem(`chat_settings_${sessionId}`);
    if (!raw) return { ...DEFAULT_SETTINGS };
    const parsed = JSON.parse(raw);
    return { ...DEFAULT_SETTINGS, ...parsed };
  } catch {
    return { ...DEFAULT_SETTINGS };
  }
}

function saveSessionSettings(sessionId, settings) {
  if (!sessionId) return;
  localStorage.setItem(`chat_settings_${sessionId}` , JSON.stringify(settings));
}

export default function ChatSettings({ sessionId, open, onClose, onChange }) {
  const [form, setForm] = useState(DEFAULT_SETTINGS);
  const [imageInput, setImageInput] = useState('');

  useEffect(() => {
    if (open) {
      const s = loadSessionSettings(sessionId);
      setForm(s);
    }
  }, [open, sessionId]);

  const update = (patch) => setForm(prev => ({ ...prev, ...patch }));

  const handleSave = () => {
    // 校验
    const t = Math.min(1, Math.max(0, Number(form.temperature ?? 0.3)));
    const normalized = { ...form, temperature: t };
    saveSessionSettings(sessionId, normalized);
    onChange?.(normalized);
    onClose?.();
  };

  return (
    <div className={`modal ${open ? 'show' : ''}`} onClick={onClose}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <div className="modal-title">对话设置</div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body settings-form">
          <div className="form-row">
            <label>模型</label>
            <select value={form.model} onChange={(e)=>update({ model: e.target.value })}>
              <option value="deepseek-v3">deepseek-v3</option>
              <option value="deepseek-r1">deepseek-r1</option>
              <option value="gpt-4o">gpt-4o</option>
            </select>
          </div>
          <div className="form-row">
            <label>温度 ({form.temperature})</label>
            <input type="range" min="0" max="1" step="0.1" value={form.temperature} onChange={(e)=>update({ temperature: Number(e.target.value) })} />
          </div>
          <div className="form-row">
            <label>系统提示词</label>
            <textarea rows={2} value={form.prompt} onChange={(e)=>update({ prompt: e.target.value })} />
          </div>
          <div className="form-row inline">
            <label>
              <input type="checkbox" checked={!!form.enableCoT} onChange={(e)=>update({ enableCoT: e.target.checked })} /> 启用思维链
            </label>
          </div>
          <div className="form-row">
            <label>CoT 模式</label>
            <select value={form.cotMode} disabled={!form.enableCoT} onChange={(e)=>update({ cotMode: e.target.value })}>
              <option value="ZERO_SHOT">ZERO_SHOT</option>
              <option value="FEW_SHOT">FEW_SHOT</option>
            </select>
          </div>
          <div className="form-row">
            <label>CoT 示例</label>
            <textarea rows={3} placeholder="仅 FEW_SHOT 使用" disabled={!(form.enableCoT && form.cotMode === 'FEW_SHOT')} value={form.cotExample} onChange={(e)=>update({ cotExample: e.target.value })} />
          </div>
          <div className="form-row">
            <label>对话模式</label>
            <select value={form.chatMode} onChange={(e)=>update({ chatMode: e.target.value })}>
              <option value="BASIC">BASIC</option>
              <option value="TASK_PLANNING">TASK_PLANNING</option>
              <option value="STREAMING_TOOLS_MANUAL">STREAMING_TOOLS_MANUAL</option>
            </select>
          </div>
          <div className="form-row inline">
            <label>
              <input type="checkbox" checked={!!form.showToolResults} disabled={form.chatMode !== 'TASK_PLANNING'} onChange={(e)=>update({ showToolResults: e.target.checked })} /> 显示工具结果（任务规划）
            </label>
          </div>
          <div className="form-row">
            <label>图片URL</label>
            <div className="image-url-box">
              <input className="image-input" placeholder="https://..." value={imageInput} onChange={(e)=>setImageInput(e.target.value)} />
              <button className="tool-btn" onClick={()=>{
                const v = imageInput.trim();
                if (!v) return;
                try { new URL(v); } catch { alert('URL不合法'); return; }
                const list = Array.isArray(form.imageUrls) ? form.imageUrls.slice() : [];
                if (list.length >= 5) { alert('最多5张图片'); return; }
                list.push(v);
                update({ imageUrls: list });
                setImageInput('');
              }}>添加</button>
            </div>
            <ul className="image-list">
              {(form.imageUrls || []).map((u, idx) => (
                <li key={u+idx}>
                  <span className="url-text">{u}</span>
                  <button className="link" onClick={()=>{
                    const list = (form.imageUrls || []).filter((x)=>x!==u);
                    update({ imageUrls: list });
                  }}>移除</button>
                </li>
              ))}
            </ul>
          </div>
        </div>
        <div className="modal-footer">
          <button className="tool-btn" onClick={()=>{ update(DEFAULT_SETTINGS); }}>恢复默认</button>
          <div style={{ flex: 1 }} />
          <button className="tool-btn" onClick={handleSave}>保存</button>
        </div>
      </div>
    </div>
  );
}

// 为避免 Fast Refresh 警告，不在此文件导出非组件方法与常量。
